import urllib2

from xml.etree.ElementTree import XML, fromstring, tostring

RSS_FEED = 'http://feeds.tvo.org/tvo/TxZN?format=xml'
itunes = '{http://www.itunes.com/dtds/podcast-1.0.dtd}'
yahoo = '{http://search.yahoo.com/mrss/}'

def readRSS():
        req = urllib2.Request(RSS_FEED)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        rssxml=response.read()
        response.close()
        #print rssxml
        return fromstring(rssxml)	# return the parsed tree

def parseEpisodeInfo(info):
	title = info.find('title').text
	summary = info.find(itunes + 'summary').text
	duration = info.find(itunes + 'duration').text
	thumbnailUrl = info.find(yahoo + 'thumbnail').attrib['url']
	mp4url = info.find(yahoo + 'content').attrib['url']
	date = info.find('pubDate').text
	
	print 'title: ' + title
	print 'summary: ' + summary
	print 'duration: ' + duration
	print 'date: ' + date
	print 'thumbnail: ' + thumbnailUrl
	print 'mp4: ' + mp4url
	print '----------------------------------------------------------------------'
	
	return {'description':summary, 'name':title, 'mp4url':mp4url, 'date':date,'duration':duration,'thumbnailUrl':thumbnailUrl}

def isRelevantEpisode(info, searchTerm):
	if info.find('title').text.upper().find(searchTerm) > -1:
		return True
	
	if info.find(itunes + 'subtitle').text.upper().find(searchTerm) > -1:
		return True
	
	if info.find(itunes + 'summary').text.upper().find(searchTerm) > -1:
		return True

	if info.find('description').text.upper().find(searchTerm) > -1:
		return True
		
	if info.find(itunes + 'keywords').text.upper().find(searchTerm) > -1:
		return True
	
	return False

def allEpisodes():
	tree = readRSS()
	
	#for i in tree[0].find('item'):
	#	print "~ " + i.tag
	
	for child in tree.iter('item'):
		info = parseEpisodeInfo(child)
		
def searchEpisodes(searchTerm):
	tree = readRSS()
	
	UsearchTerm = searchTerm.upper()
	
	for child in tree.iter('item'):
		if isRelevantEpisode(child, UsearchTerm):
			info = parseEpisodeInfo(child)
		

def latestEpisodes(num):
	tree = readRSS()
	
	count = 0
	
	for child in tree.iter('item'):
		info = parseEpisodeInfo(child)
		count  += 1
		if count >= num:
			return
	
	
def main():
	allEpisodes()
	#searchEpisodes('mpp')
	#latestEpisodes(5)
	
if __name__ == "__main__":
	main()
